<?php
/**
 *@author sparkguo 
 *@date 2017-09-22 汇率管理
 */
defined('BASEPATH') OR exit('No direct script access allowed');
ini_set('max_execution_time', '0');
class MoneyRateManage extends CI_Controller {
    
	function __construct(){
		parent::__construct();
		$this->load->model('Function_m','fun');
		//$this->load->model('EbayMessage_m','m');
		$this->pageSize =$this->config->item('pagenum');
        $this->CI =& get_instance();
        //$this->db148 = $this->CI->load->database('amazondata', TRUE);  edit by sparkguo 2019/01/09
    }

    function ajaxbutton(){
		$action = $other = $this->input->get_post('op');
		switch($action){
			case "getRateDetail":
                $this->getRateDetail();
				break; 
            case "reviseRateInfo":
                $this->reviseRateInfo();
            break;
            case "addMoneyRate":
                $this->addMoneyRate();
            break;
		}
	} 
    
    //汇率列表
    public function index(){
       
		$nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        //---处理where查询条件
        $where = "";
        $search_data=$this->input->get();
        $starttime=trim($search_data['starttime']);
        $endtime=trim($search_data['endtime']);
       
        $this->tpl->assign($tpl_data);
        if(!empty($search_data['sch_namecn'])){
            $where.=" && namecn='".$search_data['sch_namecn']."'";    
        }
        if(!empty($search_data['sch_name'])){
            $where.=" && name='".$search_data['sch_name']."'";    
        }

        $tpl_data=array("sch_namecn"=>$search_data['sch_namecn'],'sch_name'=>$search_data['sch_name'],
        'starttime'=>$starttime,'endtime'=>$endtime,'message_state'=>$search_data['message_state']);
		$list = $this->fun->getalllist("d_moneyrate", $where, $nowpage, $if_csv, $this->pageSize," order by id asc");
        
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign($tpl_data);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("rate_list", $list["list"]);
          //echo $this->db->last_query(); 
          
        $this->tpl->display("MoneyRateManage/index.tpl");
    }
    
    //编辑汇率
    public function getRateDetail(){
        $infoid=$this->input->post("id");
        $rs=$this->fun->getdatabasesdetail("d_moneyrate","AND id=".$infoid); 
        echo json_encode($rs);     
    }
    
    //
    public function reviseRateInfo(){
        $rate_id=$this->input->post("data_id");
        $witer=$_COOKIE['username'];
        $savedata=array('namecn'=>$this->input->post("namecn"),'name'=>$this->input->post("name"),
        'rate'=>$this->input->post("rate"),'descr'=>$this->input->post("descr"),'opername'=>$witer,'opertime'=>date("Y-m-d H:i:s"));
        $this->db->update('d_moneyrate', $savedata, 'id='.$rate_id); 
        //$this->db148->update('fshop.d_moneyrate', $savedata, 'id='.$rate_id);  edit by sparkguo 2019/01/09
        //$ret_json=array("state"=>'success','msg'=>'ok');
        //echo json_encode($ret_json);
        $url=$_SERVER['HTTP_REFERER'];
        echo "<script language='javascript' type='text/javascript'>alert('修改成功');location.href='$url'</script>";
        //Header("Location: $url");  
    }
    
    
    //增加币种汇率
    public function addMoneyRate(){
        $rate_id=$this->input->post("data_id");
        $witer=$_COOKIE['username'];
        $savedata=array('namecn'=>$this->input->post("namecn"),'name'=>$this->input->post("name"),
        'rate'=>$this->input->post("rate"),'descr'=>$this->input->post("descr"),'opername'=>$witer,'opertime'=>date("Y-m-d H:i:s"));
        $this->db->insert('d_moneyrate', $savedata); 
        //$this->db148->insert('fshop.d_moneyrate', $savedata); edit by sparkguo 2019/01/09
        $url=$_SERVER['HTTP_REFERER'];
        echo "<script language='javascript' type='text/javascript'>alert('新增成功');location.href='$url'</script>";
        $insertid=$this->db->insert_id();
        
    }

    public function  splitOrderList(){
        
        $platformID = intval($this->input->get_post('platformID'));
        $goods_amount=$this->input->get("goods_amount");
        $goodsku=$this->input->get("goodsku");
        $status=$this->input->get("status");
        $shopID=$this->input->get("shopID");
        $platformID=$platformID>0?$platformID:14;
        $goods_amount=$goods_amount==''?800:$goods_amount;
        
        if($goodsku){//平台
			 //$order_where .= " and A.goods_sn ='$goodsku'";
             $this->tpl->assign("goodsku", $goodsku);
        }
        if($shopID){//平台
			 $order_where .= " and B.shopid =$shopID";
        }
        if($status){//平台
			 $order_where .= " and B.order_status =$status";
        }else{
            $order_where.=' and order_status in(1,2,3,7)';    
        }
        $this->tpl->assign("shopID", $shopID);
        $this->tpl->assign("status", $status);
        $this->tpl->assign("platformID", $platformID);
        $satrtdate=date("Y-m-d",strtotime('-7 day'));  
        $lastdate=date('Y-m-d',strtotime('-3 month'));
        $starttime=$this->input->get("starttime");
        $endtime=$this->input->get("endtime");
        $starttime=$starttime==''?$satrtdate:$starttime;
        $endtime=$endtime==''?$lastdate:$endtime;
        $order_list =  $this->fun->getdatabaseslist("db_order_sell A left join db_order_list B on A.order_id=B.order_id",
        "$order_where && B.goods_amount>=$goods_amount && platformID=$platformID 
        && dates between '$endtime' and '$starttime' group by A.order_id having count(A.order_id)>=2 order by ordertime desc");
        $show_orderlist=array();
       // echo $this->db->last_query();
        foreach($order_list as $key=>$val){
            switch ($val["order_status"]) {
                case 1;
                    $val["statustext"] = '新订单';
                    break;
                case 2:
                    $val["statustext"] = '已支付';
                    break;
                case 3:
                    $val["statustext"] = '配货中';
                    break;
                case 4:
                    $val["statustext"] = '已发货';
                    break;
                case 5:
                    $val["statustext"] = '已完成';
                    break;
                case 6:
                    $val["statustext"] = '已作废';
                    break;
                case 7:
                    $val["statustext"] = '待审查';
                    break;
            }
            $val["add_time"] = date("Y-m-d H:i:s",$val["add_time"]);
            
            $numday = (time() - strtotime($val["ordertime"])) / 86400;
            $numday=$numday<1?0:intval($numday);
            $val['numday']= $numday;
            $show_orderlist[$val['order_id']]=$val; 
        }
        $all_order_id=iarray_column($order_list,'order_id');
        $order_is_str=implode(',',$all_order_id);
        if(count($all_order_id)>0){
            $where.=" and order_id in($order_is_str) and storage_id=1 ";
            $goods_list= $this->fun->getalllist('db_order_sell a left join db_goods_stock b on b.goods_id=a.goods_id '
            ,$where,1,0,20000,'order by a.rec_id desc',"b.*,a.rec_id,a.goods_id,a.order_id,a.goods_name,a.goods_sn");          
        }
        
        $newgoods=array(); 
         $goods_list['list']=$goods_list['list']==''?array():$goods_list['list']; 
        foreach($goods_list['list'] as $key=>$goodinfo){
            $newgoods[$goodinfo['order_id']][]=$goodinfo;
        }
        foreach($newgoods as $key=>$orderinfo){
            $havestock=0;$have_sku=0;
            $nothavestock=0;
            foreach($orderinfo as $index=>$val){
                if($val['stock']>0){
                    $havestock=1;    
                }
                if($val['stock']<=0){
                    $nothavestock=1;    
                }
                //查询sku
                if(!empty($goodsku)){
                    if($val['goods_sn']==$goodsku){
                        $have_sku=1;
                    }       
                }    
            }
            if($havestock>0 && $nothavestock>0){//有货与无货都存在 可拆单
                        
            }else{
                unset($show_orderlist[$val['order_id']]);        
            }
            //查单独sku
            if(!empty($goodsku)){
                if($have_sku==0){
                    unset($show_orderlist[$val['order_id']]);    
                }       
            }
        }
        
        $tpldata=array('rslist'=>$show_orderlist,'total'=>count($show_orderlist),'starttime'=>$starttime,'endtime'=>$endtime,'goods_amount'=>$goods_amount);
        $this->tpl->assign($tpldata);
        $this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop', " AND del_flag= 0 $whereshop", 'id,name', ' order by name asc'));
        $this->tpl->assign("platform", $this->fun->getdatabaseslist('db_platform'));//所有平台
        //dump($show_orderlist);
        $this->tpl->display("MoneyRateManage/splitOrderList.tpl");    
    }
    
    /***********订单合并*********/
    function mergeorder()
    {
        /****************************************
         *** 同店铺同一个客户同一个地址即为可以合并
         * select `consignee`,count(*) as count from db_order_list group by `consignee` having count>1
         ********************************/
		if($_COOKIE["userid"] == 365 || $_COOKIE["userid"]==133 || $_COOKIE["userid"]==360 || $_COOKIE["userid"]==295)
		{
			$where = " AND (country !='china' and country !='japan' and country !='Japan')";
		}else{
			$where="";
		}
        $sql = "SELECT order_sn, shopid, `consignee`,address ,tel, zipcode,COUNT( * ) AS count FROM db_order_list where (order_status = 1 or order_status =2 or order_status =7) AND order_source ='正常订单'  $where ANd consignee !='' GROUP BY  `consignee` HAVING count >1";
        $query = $this->db->query($sql);
        $dates = $query->result_array();
        foreach ($dates as $key => $rs) {
            $sql = "SELECT * FROM `db_order_list` WHERE `consignee` LIKE '" . addslashes($rs["consignee"]) . "' AND address ='".addslashes($rs['address'])."' AND zipcode='".$rs['zipcode']."' AND tel='".$rs['tel']."' AND shopid='" . $rs["shopid"] . "' AND (order_status = 1 or order_status =2 or order_status =7)  AND order_source ='正常订单' $where ";
            $query = $this->db->query($sql);
            $linkdates = $query->result_array();
            if (count($linkdates) > 1) {
                $newdates[$key] = $linkdates;
            }
        }

        if (count($newdates) > 0) {
            $newdates = array_merge($newdates);    //重新排序
            foreach ($newdates as $key => $res) {
                foreach ($res as $s => $rs) {
                    if ($key % 2 == 1) {
                        $newdates[$key][$s][color] = "#FFFFFF";
                    } else {
                        $newdates[$key][$s][color] = "#FFF9c4";
                    }
                }

            }
        }
		
        $this->tpl->assign("newdates", $newdates);
		$this->tpl->assign("usrid", $_COOKIE['userid']);
        $this->tpl->display("orderlist/mergeorder.tpl");

    }
    
    public function updateRealExpPrice(){
        set_time_limit(0);
        $exporder=$this->input->post("up_expdata");
        $diff_data=$this->input->post("diff_data");//
        $selectMonth=$this->input->post("selectMonth");
        $deliverType=$this->input->post("deliverType");
        
        $point_val=$this->input->post('point');
        if($point_val>=2 || $point_val<=0.4){
            die("折扣数据异常，大于等于2倍或小于0.4了");    
        }
        $exporderlist=json_decode($exporder,true);
        $diff_data_list=json_decode($diff_data,true);
        //isform ==1 马帮 isform ==2 新系统 isfrom ==3 海外系统
        $express_check_arr=array();
        //$sqlCount ="delete from db_express_check where check_month='$selectMonth' and express_type=$deliverType";
        //$allCount = $this->db->query($sqlCount);
        
        foreach($diff_data_list as $key=>$val){
            $check_ret=$val['weight_waring']==1?2:3;//
            if($check_ret==2){
                continue;
            }
            $diffinfo=array("exl_line"=>$val['id'],"exp_number"=>$val['deliverNumber'],"exp_date"=>$val['deliverDate'],"weight"=>$val['deliverWeight'],
            "fuman_weight"=>$val['weight'],"price"=>$val['deliverFee'],'check_ret'=>$check_ret,'check_month'=>$selectMonth,
            "fuman_price"=>$val['fee'],"order_sn"=>$val['orderId'],'express_type'=>$deliverType,
            'creator'=>$_COOKIE['username'],'createtime'=>date("Y-m-d H:i:s")
            );
            $express_check_arr[]=$diffinfo;
        }
        foreach($express_check_arr as $key=>$val){
            /*$have_shipinfo=$this->fun->getdatabasesdetail('db_express_check',
            " AND exp_number='".$val['exp_number']."' and exl_line=$val[exl_line]");
            if($have_shipinfo['id']){
                unset($val['creator']);
                $this->db->update('db_express_check', $val,' id='.$have_shipinfo['id']);  
            }else{*/
                $this->db->insert('db_express_check', $val);     
            //}
            //echo $this->db->last_query();
            //echo "<br />";    
        }
        if(!is_array($exporderlist)){
            $exporderlist=array();
        }
        foreach($exporderlist as $key=>$expinfo){
            $val=$expinfo;
            echo $key."正在更新运单号：".$expinfo['deliverNumber']."运费信息<br />";
            switch($expinfo['isform']){
                case "1":
                case "2":
                    $deliverWeight=$expinfo['deliverWeight']*1000;
                    $scanorder_updata=array("real_freight"=>$expinfo['deliverFee']);
                    $this->db->update('db_mabang_scanorder',$scanorder_updata,"batch_shipping_number='".$expinfo['deliverNumber']."'");
                    //dump($this->db->last_query()); 
                    $rsOrder = $this->fun->getdatabasesdetail('db_order_list'," AND shipping_number='".$expinfo['deliverNumber']."'");
                    //dump($this->db->last_query());
                    if($rsOrder){
                        $arr_plat['shipping_realfee']=$expinfo['deliverFee']*$point_val;
                        $arr_plat['orderweight']=$deliverWeight;
                        $this->db->update('db_order_list',$arr_plat,"shipping_number='".$expinfo['deliverNumber']."'"); //更新物流费用
                        //dump($this->db->last_query());
                        $logdata["goods_id"] = $rsOrder['order_id'];	//订单ID db_order_list
                        $logdata["updatetime"] = date("Y-m-d H:i:s");
                        $logdata["createUid"] = $_COOKIE['userid'];
                        $logdata["types"] = 3;
                        $logdata["content"] = '交运对帐，更新真实物流费为：'.$arr_plat['shipping_realfee'].',预估重量更新为对方称重：'.$deliverWeight;
                        $logdata["createUser"] =$_COOKIE['username'];
                        $this->db->insert('db_goods_log', $logdata); 
                        //dump($this->db->last_query());
                    }
                break;
                case "3":
                    $box_expinfo= $this->fun->getdatabasesdetail('t_transport_status'," AND ck='".$expinfo['deliverNumber']."'");
                    //dump($this->db->last_query());
                    if($box_expinfo['task_id']){
                        $transport_status_updata=array('freight'=>$expinfo['deliverFee']);
                        $this->db->update('t_transport_status',$transport_status_updata,"ck='".$expinfo['deliverNumber']."'");
                        //dump($this->db->last_query());
                        $sql = "SELECT sum(A.freight) as real_free,ck,task_id from t_transport_status A
                        left join t_transportationtask B on A.task_id = B.id where A.task_id=".$box_expinfo['task_id'];
                        $rsdb = $this->db->query($sql)->result_array();
                       // dump($this->db->last_query());
                        //dump($rsdb);
                        if($rsdb[0]['task_id']){
                            $task_updata=array('actual_freight'=>$rsdb[0]['real_free']);
                            $this->db->update('t_transportationtask',$task_updata,"id=".$rsdb[0]['task_id']);    
                        }
                       // dump($this->db->last_query());
                    }
                break;              
            }
            //做备忘数据
            $check_ret=$val['weight_waring']==1?2:1;//
            $diffinfo=array("exl_line"=>$val['id'],"exp_number"=>$val['deliverNumber'],"exp_date"=>$val['deliverDate'],"weight"=>$val['deliverWeight'],
            "fuman_weight"=>$val['weight'],"price"=>$val['deliverFee'],'check_ret'=>$check_ret,'check_month'=>$selectMonth,
            "fuman_price"=>$val['fee'],"order_sn"=>$val['orderId'],'express_type'=>$deliverType,
            'creator'=>$_COOKIE['username'],'createtime'=>date("Y-m-d H:i:s"));
            /*$have_shipinfo=$this->fun->getdatabasesdetail('db_express_check',
            " AND exp_number='".$diffinfo['exp_number']."' and exl_line=$diffinfo[exl_line]");
            if($have_shipinfo['id']){
                unset($diffinfo['creator']);
                unset($diffinfo['check_ret']);
                $this->db->update('db_express_check', $diffinfo,' id='.$have_shipinfo['id']);  
            }else{*/
                $this->db->insert('db_express_check', $diffinfo);     
            //}
             //echo $this->db->last_query();
            //echo "<br />";   
        }
        echo "<strong><br />所有真实物流费用更新成功</strong>";
    }
    
}
